package vaccine.appointment.system.common.advice;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import vaccine.appointment.system.common.annotation.AutoWrapResult;

/**
 * 统一响应体处理器
 * 自动将 Controller返回的数据封装到CommonResult中
 */
@Slf4j
@RestControllerAdvice
public class ResponseResultAdvice implements ResponseBodyAdvice<Object> {

    /**
     * 判断是否需要处理响应体
     * 当适用了@AutoWrapResult注解时，才需要处理响应体
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        //检查方法上是否有 @AutoWrapResult 注解
        AutoWrapResult annotation = returnType.getMethodAnnotation(AutoWrapResult.class);
        if(annotation != null) {
            return true;
        }

        //检查类上是否有 @AutoWrapResult 注解
        annotation = AnnotatedElementUtils.findMergedAnnotation(returnType.getContainingClass(), AutoWrapResult.class);
        if(annotation != null) {
            return true;
        }

        return false;
    }

    /**
     * 处理响应体
     * 对返回结果进行封装
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        //如果 body 已经是 CommonResult 类型，说明已经封装为统一结果，直接返回即可
        if(body instanceof CommonResult) {
            return body;
        }

        //将结果封装为统一结果（包括String类型）
        return CommonResult.success(body);
    }
}
